// pages/orders/orders.js
var app = getApp();
var curPage = 1;
Page({
  data: {
    orders: [],
    more: true,
    navbar: [{
      status: 0,
      name: '全部'
    }, {
      status: 1,
      name: '待支付'
    }, {
      status: 2,
      name: '待发货'
    }, {
      status: 4,
      name: '待收货'
    }, {
      status: 7,
      name: '已完成'
    }, {
      status: 6,
      name: '售后'
    }],
    navbarIndex: 0
  },
  onLoad:function(options){
    this.setData({
      windowHeight: app.systemInfo.windowHeight
    })
    if (options.status>0) {
      var navbar = this.data.navbar
      for (var i = 0; i < navbar.length; i++) {
        if (navbar[i].status == options.status) {
          this.setData({
            navbarIndex: i,
          })
        }
      }
    }
  },
  onShow:function(){
    var that = this;
    var token = wx.getStorageSync('token');
    if (!token) {
      app.util.newLogin(app,function(res){
        if(res){
          that.getOrders(curPage);
        }
      });
    }else{
      that.getOrders(curPage);
    }
  },
  showAll: function(){
    this.setData({
      showAll: true
    })
  },
  getOrders: function(page){
    var that = this;
    var statusIndex = this.data.navbarIndex;
    var status = that.data.navbar[statusIndex].status;
    wx.showLoading({
      title: '订单加载中...',
      mask: true
    });
    app.func.req('orders/index',{
      page: page,
      status: status
    },'GET',function(res){
      var orders = res.result;
      for (var i = 0; i < orders.length; i++) {
        orders[i].status_alias = app.util.orderStatus(orders[i].status);
        orders[i].created_at = app.util.orderTime(orders[i].created_at);
      }

      var curOrders = [];
      if(page == 1){
        curOrders = orders;
      }else{
        curOrders = that.data.orders.concat(orders);
      }
      that.setData({
        orders: curOrders
      })
      if (res.result.length == 0) {
        if (page == 1){
          that.setData({
            empty: true
          })
        }else{
          that.setData({
            more: false
          })
        }
      }
      wx.hideLoading();
    },{
      token: wx.getStorageSync('token')
    })
  },
  selectStatus: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    var ordersAll = this.data.ordersAll;
    this.setData({
      navbarIndex: index,
      more: true,
      scrollTop: 0
    })

    var curStatus = that.data.navbar[index].status;
    this.getOrders(1);
    curPage = 1;
  },
  loadMore: function(){
    console.log(1);
    var more = this.data.more;
    curPage++;
    if(more){
      this.getOrders(curPage);
    }
  }
})
